package com.example.demo.test;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
public class TextController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Value("${spring.datasource.driver-class-name}")
    private String driver;
    @Value("${spring.datasource.url}")
    private String url;
    @Value("${spring.datasource.username}")
    private String username;
    @Value("${spring.datasource.password}")
    private String password;

    @GetMapping("/test")
    public String test() {
        Map<String, String> map = new HashMap<>();
        map.put("redis", testRedis());
        map.put("mysql", testMysql());
        return JSONUtil.toJsonStr(map);
    }

    private String testRedis() {
        try {
            stringRedisTemplate.opsForValue().set("hello", "hello world");
            String res = stringRedisTemplate.opsForValue().get("hello");
            stringRedisTemplate.delete("hello");
            return "请求 redis 正常:" + res;
        } catch (Exception e) {
            System.out.println("请求redis异常，" +  e.getMessage());
            e.printStackTrace();
            return "redis 链接异常";
        }
    }

    private String testMysql() {
        // 用于管理数据库连接
        Connection connection = null;
        // 用于执行 SQL 语句
        Statement statement = null;
        // 用于存储查询结果
        ResultSet resultSet = null;
        try {
            // 加载驱动
            Class.forName(driver);
            // 建立连接
            connection = DriverManager.getConnection(url, username, password);
            log.info("数据库链接成功");
            // 创建statement
            statement = connection.createStatement();
            // 执行sql
            String sql = "select 1";
            resultSet = statement.executeQuery(sql);
            // 处理结果
            if (resultSet.next()) {
                return "数据库连接成功：" + resultSet.getString(1);
            }
        } catch (Exception ex) {
            System.out.println("请求数据库异常，" +  ex.getMessage());
            ex.printStackTrace();
            return "数据库链接异常";
        } finally {
            // 6. 关闭资源
            try {
                if (resultSet != null) resultSet.close();
                if (statement != null) statement.close();
                if (connection != null) connection.close();
            } catch (Exception e) {
                System.err.println("关闭资源时出错：" + e.getMessage());
            }
        }
        return "数据库连接未知";
    }

}
